/**
 * @作者 伟子涵
 * @微信公号 搬砖暗夜码农
 * @开源项目 $ https://gitee.com/zhouwei5208888
 * @我的博客 $ http://itzhouwei.com
 * @创建时间 2023/10/17 10:20
 */
package com.itzhouwei.netty.day6;

/**
 * @description:
 * @author：zw，微信：yingshengzw
 * @date: 2023/10/17
 * @Copyright： 公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、分享、成长，让自己和他人都能有所收获！
 */
public class JuDianUtil {

    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }


    public static String bytesToHexString2(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i : bytes) {
            sb.append((char) i);
        }
        String asciiString = sb.toString();
        String hexString = asciiToHex(asciiString);
        System.out.println(hexString);
        return hexString;
    }

    public static String asciiToHex(String asciiStr) {
        StringBuilder hex = new StringBuilder();
        for (int i = 0; i < asciiStr.length(); i++) {
            char ch = asciiStr.charAt(i);
            int in = (int) ch;
            String part = Integer.toHexString(in);
            hex.append(part);
        }
        return hex.toString();
    }


    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /***
     * 获取操作电桩的指令
     * @param msg
     * @return
     */
    public static String getMsgCmd(String msg) {
        int pos = 10;
        String encryptionFlag = msg.substring(pos, pos += 2);
        System.out.println("指令类型: " + encryptionFlag);
        return encryptionFlag;
    }

    /***
     * 获取桩的编码
     * @param msg
     * @return
     */
    public static String getPileNum(String msg) {
        int pos = 44;
        String pileNumber = msg.substring(pos, pos += 14);
        System.out.println("桩编号: " + pileNumber);
        return pileNumber;
    }
}
